﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using TestService.Common;
using TestService.Common.IoC;
using TestService.Contract;
using TestService.Contract.Data;

namespace TestService.ApplicationService
{
    /// <summary>
    /// 消息服务
    /// </summary>
    [IocServiceBehavior]
    public class MessageService : ApplicationBaseService, IMessageService
    {
        private static string inputQueueName = "";

        public MessageService()
        {
            inputQueueName = AppSettings.InputQueueName;
        }

        public bool Send(MessageModel model)
        {
            using (MessageQueue queue = new MessageQueue(inputQueueName, QueueAccessMode.Send))
            {
                queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
                try
                {
                    Message message = new Message(
                        GetXmlData(model));
                    Log.Info(string.Format("发送消息： {0}", message.Body.ToString()));
                    queue.Send(message);

                    return true;
                }
                catch (MessageQueueException mex)
                {
                    if (mex.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                    {
                        Log.Error(string.Format("Message queue exception occured", mex));
                    }
                    return false;
                }
                catch (Exception ex)
                {
                    // Write the message details to the Error queue
                    Log.Error(ex);
                    return false;
                }
            }
        }

        private string GetXmlData(MessageModel model)
        {
            StringBuilder sb = new StringBuilder("<realtimeEvent>");
            sb.AppendFormat("<eventName>ClientDealEvent</eventName>");
            sb.AppendFormat("<messageId>{0}</messageId>", model.MessageId);
            sb.AppendFormat("<createTime>{0}</createTime>", model.CreateTime);
            sb.AppendFormat("<content>{0}</content>", model.Content);
            sb.AppendLine("</realtimeEvent>");
            return sb.ToString();
        }
    }
}
